package com.yun.zf.system.security.filter;

import com.yun.zf.common.utils.StringUtils;
import com.yun.zf.system.exception.CustomException;
import com.yun.zf.system.security.token.MobileCodeAuthenticationToken;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.security.authentication.AbstractAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.authentication.AbstractAuthenticationProcessingFilter;
import org.springframework.web.servlet.HandlerExceptionResolver;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class MobileCodeAuthenticationFilter extends AbstractAuthenticationProcessingFilter {
    @Autowired
    @Qualifier("handlerExceptionResolver")
    private HandlerExceptionResolver resolver;


    public MobileCodeAuthenticationFilter() {
        super("/codeLogin");//认证url
    }


    @Override
    public Authentication attemptAuthentication(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse) throws AuthenticationException, IOException, ServletException {

        String mobile = httpServletRequest.getParameter("mobile");
        String code =httpServletRequest.getParameter("code");


        if (StringUtils.isBlank(mobile)) {
            resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("手机号码不能为空"));
            return null;
        }
        if (StringUtils.isBlank(code)) {
            resolver.resolveException(httpServletRequest, httpServletResponse, null, new CustomException("验证码不能为空"));
            return null;
        }
        AbstractAuthenticationToken authRequest =   new MobileCodeAuthenticationToken(mobile, code);

        //把账号密码封装成token，传给manager认证
        return getAuthenticationManager().authenticate(authRequest);

    }

}
